import * as wsConst from './types'

// Note: 使用类继承的方式进行扩展，在safari浏览器上无法获取扩展方法
function defineProperties (target, props) {
  Object.keys(props).forEach((propName) => {
    const descriptor = {
      value: props[propName]
    }
    Object.defineProperty(target, propName, descriptor)
  })
}

const protoProps = {
  _send (sendData) {
    if (this.readyState === 1) {
      this.send(JSON.stringify(sendData))
    } else {
      const timeId = setInterval(() => {
        if (this.readyState === 1) {
          this.send(JSON.stringify(sendData))
          clearInterval(timeId)
        }
      }, 300)
    }
  },
  ping () {
    const sendData = {
      id: wsConst.PING,
      method: 'server.ping',
      params: []
    }
    // 初估server的session保持为10分钟，基于此设置每5分钟ping一次
    const timerId = setInterval(() => {
      if (this.readyState === 1) {
        console.log('ping')
        this.send(JSON.stringify(sendData))
      } else {
        clearInterval(timerId)
      }
    }, 10000)
  },
  // 实时行情
  subscribeToday (coinPairData) {
    const sendData = {
      id: 2,
      method: 'today.subscribe',
      params: Object.keys(coinPairData)
    }
    this._send(sendData)
  },
  /**
 * 最新成交
 * @param {*array} symbolList 如：ETHBTC
 */
  subscribeDeals (symbolList) {
    const sendData = {
      id: 2,
      method: 'deals.subscribe',
      params: symbolList
    }
    this._send(sendData)
  },
  // 深度,参数：交易对 条数 间隔
  subscribeDepth ({ symbol, limit, interval }) {
    const sendData = {
      id: 17,
      method: 'depth.subscribe',
      params: [symbol, limit || 30, interval || '0']
    }
    this._send(sendData)
  },
  // 订阅委托
  subscribeOrder ({ stock, money }) {
    const sendData = {
      id: 33,
      method: 'order.subscribe',
      params: [this.stock + this.money]
    }
    this._send(sendData)
  },
  // 查询当前委托
  queryOrder ({ symbol }) {
    const sendData = {
      id: wsConst.ORDER_QUERY_ID,
      method: 'order.query',
      params: [symbol, 0, 50]
    }
    this._send(sendData)
  },
  // 查询历史委托 @auth
  queryHistoryOrder ({ symbol, offset = 0, limit = 10 }) {
    const sendData = {
      id: wsConst.ORDER_HISTORY_ID,
      method: 'order.history',
      params: [symbol, 0, 0, offset, limit, 0]
    }
    this._send(sendData)
  },

  auth ({ accessToken, platform = 'android' }) {
    console.log('auth', accessToken, platform);
    const sendData = {
      id: wsConst.SERVER_AUTH_ID,
      method: 'server.auth',
      params: [accessToken, platform]
    }
    this._send(sendData)
  }
}

defineProperties(WebSocket.prototype, protoProps)

export const TYPES = wsConst
export default WebSocket
